let allStatus;
let heart = 0;
let heart2 = 0;
let timeOut = 5000;
let water_time = 1000; // 默认关水延迟
let water2_time = 2000; // 默认关水延迟
let tolerance = timeOut * 2;
let path = '/' + sessionStorage.getItem('unm');

document.getElementById("image").addEventListener("dblclick", up_image); // 双击图片退出登陆
// document.getElementById("image").addEventListener("click", up_image); // 双击图片退出登陆
document.getElementById("login_btn").addEventListener("click", lslogin); // 登陆按钮
$("#set_w1_timer").val(water_time / 1000);
$("#set_w2_timer").val(water2_time / 1000);

const fileInputs = document.querySelector('.fileDoms')
function up_image(){
    fileInputs.click()
}

// 上传图片 //
function changeFile() {
    console.log("上传")
    let reader = new FileReader();
    reader.readAsArrayBuffer(fileInputs.files[0]);
    reader.onload = function(a){
        // img.src = a.target.result; //等同于reader.result
        // document.getElementById("image").src = a.target.result;
        // client.publish(path + '/image_esp',"11dlkfjd;fkjdslk;fjdskfjdklfjd;fjdklfj;lkfj;fkljds;kfjdsa;kfljds;fkljdskf;jds;kflj22", {qos: 0,retain: false});
        client.publish(path + '/image_esp',new Uint8Array(reader.result), {qos: 0,retain: false});
        console.log(new Uint8Array(reader.result));  
    }

} 

function w_timer(No, value) {
    let val = value * 1000;
    switch (No) {
        case "water":
            water_time = val;
            lt1.show();
            break;
        case "water2":
            water2_time = val;
            lt1.show();
            break;
        default:
            break;
    }
} // 手动设定关水延迟

// 登陆 //
function lslogin() {
    $("#user").removeAttr("style");
    $("img").attr("style", "display:none");
    $("#login_btn").text("未登陆");
    $("#lock").attr("disabled", "disabled");
    sessionStorage.clear();
    $("#st").text("已断开");
    client.end();
} // 登陆 & 断连

function login() {
    let unm = $("#username").val();
    let pwd = $("#password").val();
    if (unm && pwd) {
        sessionStorage.setItem('unm', unm);
        sessionStorage.setItem('pwd', pwd);
    }
    // $("img").removeAttr("style");
    // $("#user").attr("style", "display:none");
    location.reload();
}

function logout() {
    sessionStorage.clear();
} // 登出



// 开关水 //


function start_timer(time) {
    let count = 100;
    $("li").addClass("ss2");
    let text = $("#water_span").text();
    $("#st2").text(text + "进行中");
    setInterval(function() {
        count--;
        if (count >= 0) {
            document.getElementById("water").style.width = count + "%";
        };
    }, time / count);
} // 开始water的进度动画

function start_timer2(time) {
    let count2 = 100;
    $("li").addClass("ss2");
    let text = $("#water2_span").text();
    $("#st2_2").text(text + "进行中");
    setInterval(function() {
        count2--;
        if (count2 >= 0) {
            document.getElementById("water2").style.width = count2 + "%";
        }
    }, time / count2);
} // 开始water2的进度动画

function water(No) {
    switch (No) {
        case "water":
            start_timer(water_time);
            client.publish(path + '/water1', 'on');

            setTimeout(() => {
                client.publish(path + '/water1', 'off');
                $("li").removeClass("ss2");
                $("#st2").text("⌛️结束, 关水中");
                setTimeout(() => {
                    $("#st2").text("");
                }, 1000);
            }, water_time);

            break;

        case "water2":
            start_timer2(water2_time);
            client.publish(path + '/water2', 'on');


            setTimeout(() => {
                client.publish(path + '/water2', 'off');
                $("li").removeClass("ss2");
                $("#st2_2").text("⌛️结束, 关水中");
                setTimeout(() => {
                    $("#st2_2").text("");
                }, 1000);
            }, water2_time);

            break;

        default:
            break;
    }
}


function water_sw1(params) {
    
    switch (document.getElementById("water_sw1").checked) {
        case false:
            // light_off();
            document.getElementById("water_sw1").checked = true;
            client.publish(path + '/water1', 'off', {qos: 0,retain: false});
            setTimeout(() => {
                client.publish(path + '/status_out', 'status_out', { qos: 0, retain: false });
            }, 10);
            
            console.log('熄灯');
            // setTimeout(() => {
            //     light(0);
            // }, 1000);
            break;

        case true:
            // light_on();
            document.getElementById("water_sw1").checked = false;
            client.publish(path + '/water1', 'on', {qos: 0,retain: false});
            setTimeout(() => {
                client.publish(path + '/status_out', 'status_out', { qos: 0, retain: false });
            }, 10);
            console.log('开灯!');
            // setTimeout(() => {
            //     light(1);
            // }, 1000);
            break;

        default:
            break;
    }    

} 


function water_sw2(params) {
    
    switch (document.getElementById("water_sw2").checked) {
        case false:
            // light_off();
            document.getElementById("water_sw2").checked = true;
            client.publish(path + '/water2', 'off', {qos: 0,retain: false});
            setTimeout(() => {
                client.publish(path + '/status_out', 'status_out', { qos: 0, retain: false });
            }, 10);
            
            console.log('熄灯');
            // setTimeout(() => {
            //     light(0);
            // }, 1000);
            break;

        case true:
            // light_on();
            document.getElementById("water_sw2").checked = false;
            client.publish(path + '/water2', 'on', {qos: 0,retain: false});
            setTimeout(() => {
                client.publish(path + '/status_out', 'status_out', { qos: 0, retain: false });
            }, 10);
            console.log('开灯!');
            // setTimeout(() => {
            //     light(1);
            // }, 1000);
            break;

        default:
            break;
    }    

} 

// 开关灯 //
function sw(params) {
    
    switch (document.getElementById("output").checked) {
        case false:
            // light_off();
            document.getElementById("output").checked = true;
            client.publish(path + '/light', 'off', {qos: 0,retain: true});
            setTimeout(() => {
                client.publish(path + '/status_out', 'status_out', { qos: 0, retain: false });
            }, 10);
            
            console.log('熄灯');
            // setTimeout(() => {
            //     light(0);
            // }, 1000);
            break;

        case true:
            // light_on();
            document.getElementById("output").checked = false;
            client.publish(path + '/light', 'on', {qos: 0,retain: true});
            setTimeout(() => {
                client.publish(path + '/status_out', 'status_out', { qos: 0, retain: false });
            }, 10);
            console.log('开灯!');
            // setTimeout(() => {
            //     light(1);
            // }, 1000);
            break;

        default:
            break;
    }    

} // 开关状态

// 打开、关闭 //
function open_btn_clock(params) {
    
    client.publish(path + '/open_btn', '1', {qos: 0,retain: false});   

} 

// 上一张 //
function last_btn_clock(params) {
    
    client.publish(path + '/last_pic_btn', '1', {qos: 0,retain: false});   

} 
// 下一张 //
function next_btn_clock(params) {
    
    client.publish(path + '/next_pic_btn', '1', {qos: 0,retain: false});   

} 

// 播放照片 //
function pic_btn_clock(params) {
    
    client.publish(path + '/pic_btn', '1', {qos: 0,retain: false});   

} 

// 播放视频 //
function video_btn_clock(params) {
    
    client.publish(path + '/video_btn', '1', {qos: 0,retain: false});   

} 

function light(s) {
    if (allStatus.light == s) {
        console.log('操作成功');
    } else {
        console.log('操作失败');
        switch (s) {
            case 1:
                console.log("ccc");
                break;

            case 0:
                console.log("ddd");
                break;

            default:
                break;
        }
    }
} // 判断开关状态



// 将在全局初始化一个 mqtt 变量
// console.log(mqtt)
const options = {
    username: sessionStorage.getItem('unm'),
    password: sessionStorage.getItem('pwd'),
}
const client = mqtt.connect('wss://plant.qinzr.top:8017/mqtt', options)

setInterval(() => {
    client.publish(path + '/status_out', 'status_out', { qos: 0, retain: false });

    if (sessionStorage.getItem('error') != "1") {
        heart2 += 1;
        reConnectingStyle(); // 恢复已连接样式
        // console.log("heart2 += 1")
    }

    if (heart2 - heart <= tolerance / 1000) {

    } else {
        // console.log("检测到未连接");
        console.log("判活中" + (heart2 - heart));
        // new LightTip('未连接', 500, 'error'); 234
        $("#st").text("断线");
        DisConnectedStyle()
    }

}, timeOut); // 判活



client.on('connect', function() {
        sessionStorage.removeItem('error');
        $("#lock").removeAttr("disabled");
        // client.publish(path + '/water1', 'off');
        // client.publish(path + '/water2', 'off');
        // console.log("关水中") // 意外断开后关水

        console.log('Connected');
        $("#output").removeAttr("disabled");

        $("#login_btn").text("退出登陆");

        client.subscribe(path + '/image_phone', {
            qos: 0
        }, function(error, granted) {
            if (error) {
                console.log(error);
            } else {
                // client.publish(path + '/img_out', 'img_out')
                console.log(`${granted[0].topic} was subscribed`)
            }
        })

        client.subscribe(path + '/light', {
            qos: 0
        });

        client.subscribe(path + '/status_in', {
            qos: 0
        }); // 订阅所有状态
        
        // setTimeout(() => {
        //     client.publish(path + '/img_out', 'img_out', { qos: 0, retain: false });
        // }, 2000);



    }) // 连接成功, 订阅放里面



client.on('reconnect', function() {
        console.log('Reconnecting...');
        client.publish(path + '/water1', 'off');
        client.publish(path + '/water2', 'off');
        console.log("关水中") // 意外断开后关水
    }) //当断开连接后，经过重连间隔时间重新自动连接到 Broker 时触发

client.on('error', function(error) {
        console.log(error);
        $("#ua_error").text(": 认证失败 , 请重新登录");
        DisConnectedStyle();
        sessionStorage.setItem('error', "1"); // 
        // new LightTip('认证失败, 请重新登陆', {
        //     time: 4000
        // });
        // import lightTip from './LightTip.js';
        // lightTip.success('成功');
    }) // 当客户端无法成功连接时或发生解析错误时触发

client.on('close', function() {
        console.log('Disconnected')
            // new LightTip('未连接', 1000, 'error'); 234
    }) // 在断开连接以后触发

client.on('offline', function() {
        console.log('offline');
        // new LightTip('未连接', 1000, 'error'); 234
    }) // 当客户端下线时触发

client.on('disconnect', function(packet) {
        console.log(packet);
    }) //在收到 Broker 发送过来的断开连接的报文时触发

client.on('message', function(topic, payload, packet) {
    // console.log(topic, payload, packet);
    switch (topic) {
        case path + "/status_in":
            heart = heart2;
            allStatus = JSON.parse(payload);

            // console.clear();
            console.log("当前状态:" + timeOut);
            console.log(allStatus);
            if (payload) {
                heart += 1;
                // console.log(heart);
                switch (allStatus["light"]) {
                    case 1:
                        document.getElementById("output").value = "1";
                        document.getElementById("output").checked = true;
                        break;
                    case 0:
                        document.getElementById("output").value = "0";
                        document.getElementById("output").checked = false;
                        break;
                    default:
                        break;
                }                
                
                switch (allStatus["water1"]) {
                    
                    case 1:
                        document.getElementById("water_sw1").checked = true;
                        break;
                    case 0:
                        document.getElementById("water_sw1").checked = false;
                        break;
                    default:
                        break;                    
                }

                switch (allStatus["water2"]) {
                    case 1:
                        document.getElementById("water_sw2").checked = true;
                        break;
                    case 0:
                        document.getElementById("water_sw2").checked = false;
                        break;
                    default:
                        break; 
                }


            };

            break; //获取状态

        case path + "/image_phone":
            var imgCode = 'data:image/jpg;base64,';
            var Base64Image = Base64.fromUint8Array(payload);
            console.log(payload);

            document.getElementById("image").src = imgCode + Base64Image;

            break;

        default:
            break;
    }
    if (topic == path + '/img_in') {

    }
    // Payload is Buffer
})



function changeSrc() {
    client.publish(path + '/img_out', 'img_out');
} // 拍照

function light_on() {
    client.publish(path + '/light', 'on', {
        qos: 0,
        retain: true
    });
}

function light_off() {
    client.publish(path + '/light', 'off', {
        qos: 0,
        retain: true
    });
}

// function water_on() {
//     client.publish(path + '/water', 'on');
// }

// function water2_on() {
//     client.publish(path + '/water2', 'on');
// }

// function water_off() {
//     client.publish(path + '/water', 'off');
// }

// function water2_off() {
//     client.publish(path + '/water2', 'off');
// }


// 样式 //

function DisConnectedStyle() {
    $("[class='switch']").attr("style", "display:none");
    $("li").addClass("ss");
} // 断连样式

function reConnectingStyle() {
    $("[class='switch']").removeAttr("style");
    $("li").removeClass("ss");
    $("#st").text("***" + sessionStorage.getItem('unm').substring(sessionStorage.getItem('unm').length - 1) + "已上线");

} // 取消断连样式

function unclock() {
    client.publish(path + '/water1', 'off');
    client.publish(path + '/water2', 'off');
    // $("li").removeClass("ss2");
    // $("li").removeClass("ss");
    location.reload();
}